<template>
  <div class="script-management">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input 
            v-model="filters.content" 
            placeholder="请输入内容关键词"
            allow-clear
            @change="loadScripts"
          />
        </a-col>
        <a-col :span="4">
          <a-select 
            v-model="filters.nodenum" 
            placeholder="选择章节"
            allow-clear
            @change="loadScripts"
          >
            <a-option :value="0">E0 导入</a-option>
            <a-option :value="1">E1 探寻重复消极思维</a-option>
            <a-option :value="2">E2 认识价值与行动选择</a-option>
            <a-option :value="3">E3 跟消极想法说再见</a-option>
            <a-option :value="4">E4 做想法的旁观者</a-option>
            <a-option :value="5">E5 探寻自我与生活方向</a-option>
            <a-option :value="6">E6 行动指南</a-option>
            <a-option :value="7">E7 结束</a-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select 
            v-model="filters.answertype" 
            placeholder="问题类型"
            allow-clear
            @change="loadScripts"
          >
            <a-option value="T">系统文本</a-option>
            <a-option value="C">用户选择</a-option>
          </a-select>
        </a-col>
        <a-col :span="10">
          <a-space>
            <a-button type="primary" @click="loadScripts">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="resetFilters">重置</a-button>
            <a-button type="primary" @click="showCreateModal">
              <template #icon>
                <IconPlus />
              </template>
              新增
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>
    
    <!-- 脚本表格 -->
    <a-table 
      :data="filteredScripts" 
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #columns>
        <a-table-column title="ID" data-index="id" :width="60" />
        <a-table-column title="章节" data-index="nodenum" :width="200">
          <template #cell="{ record }">
            {{ getChapterTitle(record.nodenum) }}
          </template>
        </a-table-column>
        <a-table-column title="编号信息" :width="140">
          <template #cell="{ record }">
            <div class="number-info">
              <div>问题: {{ record.answernum }}</div>
              <div class="next-number">下一题: {{ record.next_answernum || '-' }}</div>
            </div>
          </template>
        </a-table-column>
        <a-table-column title="类型" data-index="answertype" :width="80">
          <template #cell="{ record }">
            <a-tag :color="record.answertype === 'T' ? 'blue' : 'green'">
              {{ record.answertype === 'T' ? '系统文本' : '用户选择' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="内容" data-index="content">
          <template #cell="{ record }">
            <div class="content-preview">
              {{ record.content.length > 50 ? record.content.substring(0, 50) + '...' : record.content }}
            </div>
          </template>
        </a-table-column>
        <a-table-column title="操作" :width="100">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" size="small" @click="showEditModal(record)">
                <template #icon>
                  <IconEdit />
                </template>
              </a-button>
              <a-button type="text" size="small" status="danger" @click="deleteScript(record)">
                <template #icon>
                  <IconDelete />
                </template>
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
    
    <!-- 创建/编辑弹窗 -->
    <a-modal 
      v-model:visible="modalVisible" 
      :title="modalTitle"
      width="600px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :model="form" :rules="rules" layout="vertical" ref="formRef">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="章节编号" field="nodenum" required>
              <a-select v-model="form.nodenum" placeholder="选择章节">
                <a-option :value="0">E0 导入</a-option>
                <a-option :value="1">E1 探寻重复消极思维</a-option>
                <a-option :value="2">E2 认识价值与行动选择</a-option>
                <a-option :value="3">E3 跟消极想法说再见</a-option>
                <a-option :value="4">E4 做想法的旁观者</a-option>
                <a-option :value="5">E5 探寻自我与生活方向</a-option>
                <a-option :value="6">E6 行动指南</a-option>
                <a-option :value="7">E7 结束</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="问题编号" field="answernum" required>
              <a-input-number v-model="form.answernum" :min="1" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="问题类型" field="answertype" required>
              <a-select v-model="form.answertype" placeholder="选择类型">
                <a-option value="T">系统文本</a-option>
                <a-option value="C">用户选择</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="下一题编号" field="next_answernum">
              <a-input-number 
                v-model="form.next_answernum" 
                :min="0" 
                placeholder="0表示结束"
                style="width: 100%" 
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="内容" field="content" required>
          <a-textarea 
            v-model="form.content" 
            placeholder="请输入内容"
            :rows="4"
          />
        </a-form-item>
        
        <a-form-item label="图片路径" field="img">
          <a-input 
            v-model="form.img" 
            placeholder="请输入图片路径，如：/images/01.png"
          />
          <template #extra>
            <div class="form-extra">
              图片需放在 public/images/ 文件夹中，路径格式必须为：/images/文件名.png
            </div>
          </template>
        </a-form-item>
        
        <a-form-item label="计时器（秒）" field="timer">
          <a-input-number 
            v-model="form.timer" 
            :min="0" 
            placeholder="留空表示无计时器"
            style="width: 100%" 
          />
          <template #extra>
            <div class="form-extra">
              设置倒计时秒数，时间结束后自动跳转到下一题。留空表示不使用计时器。
            </div>
          </template>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus, IconEdit, IconDelete, IconSearch } from '@arco-design/web-vue/es/icon'
import { scriptApi } from '../../api'

const loading = ref(false)
const modalVisible = ref(false)
const isEditing = ref(false)
const formRef = ref()

const scripts = ref<any[]>([])
const filters = reactive({
  content: '',
  nodenum: undefined,
  answertype: undefined
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true
})

const form = reactive({
  id: undefined as number | undefined,
  nodenum: undefined as number | undefined,
  answernum: undefined as number | undefined,
  content: '',
  answertype: undefined as string | undefined,
  next_answernum: undefined as number | undefined,
  img: '',
  timer: undefined as number | undefined
})

const rules = {
  nodenum: [{ required: true, message: '请选择章节' }],
  answernum: [{ required: true, message: '请输入问题编号' }],
  content: [{ required: true, message: '请输入内容' }],
  answertype: [{ required: true, message: '请选择问题类型' }]
}

const modalTitle = computed(() => isEditing.value ? '编辑脚本' : '新增脚本')

// 章节标题映射
const chapterTitles = {
  0: 'E0 导入',
  1: 'E1 探寻重复消极思维',
  2: 'E2 认识价值与行动选择',
  3: 'E3 跟消极想法说再见',
  4: 'E4 做想法的旁观者',
  5: 'E5 探寻自我与生活方向',
  6: 'E6 行动指南',
  7: 'E7 结束'
}

const getChapterTitle = (nodenum: number) => {
  return chapterTitles[nodenum as keyof typeof chapterTitles] || `第${nodenum}章`
}

const filteredScripts = computed(() => {
  let result = scripts.value
  
  if (filters.content) {
    result = result.filter(script => 
      script.content.toLowerCase().includes(filters.content.toLowerCase())
    )
  }
  
  if (filters.nodenum !== undefined && filters.nodenum !== null) {
    result = result.filter(script => script.nodenum === filters.nodenum)
  }
  
  if (filters.answertype) {
    result = result.filter(script => script.answertype === filters.answertype)
  }
  
  // 分页
  const start = (pagination.current - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  pagination.total = result.length
  
  return result.slice(start, end)
})

const loadScripts = async () => {
  loading.value = true
  try {
    const response = await scriptApi.getAllScripts()
    if (response.success) {
      scripts.value = response.data
    } else {
      Message.error(response.message || '加载脚本失败')
    }
  } catch (error) {
    console.error('加载脚本失败:', error)
    Message.error('加载脚本失败')
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  filters.content = ''
  filters.nodenum = undefined
  filters.answertype = undefined
  pagination.current = 1
}

const showCreateModal = () => {
  isEditing.value = false
  resetForm()
  modalVisible.value = true
}

const showEditModal = (record: any) => {
  
  isEditing.value = true
  Object.assign(form, {
    id: record.id,
    nodenum: record.nodenum,
    answernum: record.answernum,
    content: record.content,
    answertype: record.answertype,
    next_answernum: record.next_answernum,
    img: record.img || '',
    timer: record.timer
  })
  
  modalVisible.value = true
}

const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    nodenum: undefined,
    answernum: undefined,
    content: '',
    answertype: undefined,
    next_answernum: undefined,
    img: '',
    timer: undefined
  })
}

const handleModalOk = async () => {
  try {
    
    try {
      await formRef.value?.validate()
      
      // Arco Design 的 validate 方法在验证失败时会抛出异常
      // 如果没有抛出异常，说明验证通过
    } catch (validationError) {
      return
    }
    
    if (isEditing.value) {
      // 准备发送给后端的数据，排除 id 字段
      const updateData = {
        nodenum: form.nodenum,
        answernum: form.answernum,
        content: form.content,
        answertype: form.answertype,
        next_answernum: form.next_answernum,
        img: form.img,
        timer: form.timer
      }
      
      
      const response = await scriptApi.updateScript(form.id!, updateData)
      
      if (response.success) {
        Message.success('更新成功')
        modalVisible.value = false
        await loadScripts()
      } else {
        Message.error(response.message || '更新失败')
      }
    } else {
      // 准备发送给后端的数据，排除 id 字段
      const createData = {
        nodenum: form.nodenum,
        answernum: form.answernum,
        content: form.content,
        answertype: form.answertype,
        next_answernum: form.next_answernum,
        img: form.img,
        timer: form.timer
      }
      
      
      const response = await scriptApi.createScript(createData)
      
      if (response.success) {
        Message.success('创建成功')
        modalVisible.value = false
        await loadScripts()
      } else {
        Message.error(response.message || '创建失败')
      }
    }
  } catch (error: any) {
    console.error('保存失败 - 完整错误信息:', error)
    console.error('错误类型:', typeof error)
    console.error('错误消息:', error.message)
    console.error('错误堆栈:', error.stack)
    Message.error('保存失败: ' + (error.message || '未知错误'))
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

const deleteScript = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条脚本吗？此操作不可恢复。',
    onOk: async () => {
      try {
        const response = await scriptApi.deleteScript(record.id)
        if (response.success) {
          Message.success('删除成功')
          await loadScripts()
        } else {
          Message.error(response.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        Message.error('删除失败')
      }
    }
  })
}

const handlePageChange = (page: number) => {
  pagination.current = page
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
}

onMounted(() => {
  loadScripts()
})
</script>

<style scoped>
.script-management {
  padding: 24px;
}

.filter-section {
  background: white;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid #e5e6eb;
}

.content-preview {
  line-height: 1.4;
  word-break: break-all;
}

.number-info {
  font-size: 12px;
  line-height: 1.4;
}

.next-number {
  color: #86909c;
  margin-top: 2px;
}

:deep(.arco-table) {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.arco-table-th) {
  background: #f7f8fa;
  font-weight: 600;
}
</style>
